package com.leo.foodmaster.commons.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.leo.foodmaster.admin.system.entity.UserBean;
import com.leo.foodmaster.commons.constants.AuthConstants;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * Jwt token工具类
 * </p>
 *
 * @author ：Leo
 * @since ：2021-06-18 15:14
 */
@Slf4j
@Component
public class TokenUtils {

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(UserBean loginUser) {
        Map<String, Object> claims = new HashMap<>(1);
        claims.put(AuthConstants.USER_INFO, loginUser);
        return createToken(claims);
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setId(IdUtil.fastUUID())
                .setIssuedAt(new Date())
                .setExpiration(DateUtil.offsetMillisecond(new Date(), AuthConstants.JWT_EXPIRE_TIME))
                .compressWith(CompressionCodecs.DEFLATE)
                .signWith(SignatureAlgorithm.HS512, AuthConstants.JWT_SECRET).compact();
    }

    /**
     * 验证token
     * @param token token
     */
    public void validateToken(String token) {
        Jwts.parser().setSigningKey(AuthConstants.JWT_SECRET).parseClaimsJws(token);
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    public Claims getClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(AuthConstants.JWT_SECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取登录用户信息
     *
     * @param token 令牌
     * @return 登录用户
     */
    public UserBean getLoginUserFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        Object object = claims.get(AuthConstants.USER_INFO);
        UserBean userBean = new UserBean();
        BeanUtil.copyProperties(object, userBean);
        return userBean;
    }

    /**
     * 从令牌中获取用户权限集合
     *
     * @param token 令牌
     * @return 用户名
     */
    public Collection<GrantedAuthority> getAuthoritiesFromToken(String token) {
        UserBean user = getLoginUserFromToken(token);
        return Arrays.stream(user.getRoles().split(StrUtil.COMMA))
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    /**
     * 获取请求token
     *
     * @param request 请求
     * @return token
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(AuthConstants.JWT_HEADER);
        if (StrUtil.isNotEmpty(token) && token.startsWith(AuthConstants.JWT_PREFIX)) {
            token = token.replace(AuthConstants.JWT_PREFIX, "");
        }
        return token;
    }
}
